package com.atdel.demo30;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

/**
 * 自定义异常类，用于参数校验失败时抛出
 */
class ParameterValidationException extends RuntimeException {
    // 构造函数，用于初始化异常信息
    public ParameterValidationException(String message) {
        super(message);
    }
}

/**
 * @BelongsProject: java_study
 * @BelongsPackage: com.atdel.demo30
 * @Author: Del
 * @CreateTime: 2025-03-30  16:34
 * @Description:
 * 在getSum方法中，使用上面定义的注解，
 * 用于控制参数n的上限，如果超出n，则抛出异常提示
 * @Version: 1.0
 */
public class ParaAtsTest {

    public static final int MAX_VALUE = 100;

    /**
     * 计算从 0 到 n 的累加和
     *
     * @param n 输入参数，必须为非负数且不大于注解指定的最大值
     * @return 累加和
     * @throws ParameterValidationException 如果参数 n 不符合要求
     */
    public int getSum(@ParaAts(value = MAX_VALUE) int n) throws NoSuchMethodException {
        // 获取方法对象
        Method method = ParaAtsTest.class.getDeclaredMethod("getSum", int.class);
        // 获取参数上的注解
        Annotation[][] parameterAnnotations = method.getParameterAnnotations();
        // 获取第一个参数（n）的注解
        ParaAts paraAts = null;
        for (Annotation annotation : parameterAnnotations[0]) {
            if (annotation instanceof ParaAts) {
                paraAts = (ParaAts) annotation;
                break;
            }
        }

        if (paraAts == null) {
            throw new IllegalStateException("未找到 @ParaAts 注解");
        }

        if (n < 0) {
            throw new ParameterValidationException("参数n不能小于0");
        }
        if (n > paraAts.value()) {
            throw new ParameterValidationException("参数n不能大于" + paraAts.value());
        }
        int sum = 0;
        for (int i = 0; i <= n; i++) {
            sum += i;
        }
        return sum;
    }

    public static void main(String[] args) {
        ParaAtsTest paraAtsTest = new ParaAtsTest();
        try {
            System.out.println(paraAtsTest.getSum(100));
            System.out.println(paraAtsTest.getSum(101));
            System.out.println(paraAtsTest.getSum(-1));
        } catch (ParameterValidationException e) {
            System.err.println("参数校验失败: " + e.getMessage());
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
    }
}